package com.sskj.cndragon.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.cndragon.R;
import com.sskj.cndragon.bean.AddressBean;
import com.sskj.cndragon.bean.AssetBean;
import com.sskj.cndragon.bean.DragonBean;
import com.sskj.cndragon.bean.NoticeBean;
import com.sskj.cndragon.bean.RushDragonBean;
import com.sskj.cndragon.bean.UpdataBean;
import com.sskj.cndragon.component.DaggerUserDataComponent;
import com.sskj.cndragon.http.HttpConfig;
import com.sskj.cndragon.presenter.MainPresenter;
import com.sskj.cndragon.ui.fragment.AppUpDateFragment;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.base.AppManager;
import com.sskj.common.box.decoration.DividerHorizenLineItemDecoration;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

@Route(path = RConfig.APP_MAIN)
public class MainActivity extends BaseActivity<MainPresenter> {
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.tv_quan)
    TextView tvQuan;
    @BindView(R.id.tv_shuijing)
    TextView tvShuijing;
    @BindView(R.id.tvNotice)
    TextSwitcher tvNotice;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_dragon)
    ImageView ivDragon;
    @BindView(R.id.iv_turntable)
    ImageView ivTurnTable;
    @BindView(R.id.tv_dragon_name)
    TextView tvDragonName;
    @BindView(R.id.tv_dragon_days)
    TextView tvDragonDays;
    @BindView(R.id.tv_dragon_income)
    TextView tvDragonIncome;
    @BindView(R.id.tv_dragon_money)
    TextView tvDragonMoney;
    @BindView(R.id.view_click)
    View viewClick;
    @BindView(R.id.tv_dragon_status)
    TextView tvDragonStatus;
    @BindView(R.id.tv_dragon_times)
    TextView tvDragonTimes;
    @BindView(R.id.view_gerenziliao)
    View viewGerenziliao;
    @BindView(R.id.view_zhanghaoanquan)
    View viewZhanghaoanquan;
    @BindView(R.id.view_zhanghaozichan)
    View viewZhanghaozichan;
    @BindView(R.id.view_dingdanguanli)
    View viewDingdanguanli;
    @BindView(R.id.view_wodetuandui)
    View viewWodetuandui;
    @BindView(R.id.view_tuichu)
    View viewTuichu;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_count_down)
    TextView tvCountDown;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @Inject
    UserViewModel userViewModel;

    private UserData userData;

    private SlimAdapter<DragonBean> slimAdapter;
    private List<Integer> isCheck = new ArrayList<>();

    private Disposable noticeDispo;
    private NoticeBean noticeBean;

    //当前选中龙信息
    private String dragonName;
    private String dragonID;
    private String draggonMoney;
    private String dragonDays;
    private String yuyueMoney;
    private String qianggouMoney;

    private int dragonStatus;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresenter getPresenter() {
        return new MainPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        DaggerUserDataComponent.create().inject(this);

        tvNotice.setFactory(() -> {
            TextView textView = new TextView(this);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PT, 26);
            textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setSingleLine();
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(ContextCompat.getColor(App.INSTANCE, R.color.app_l0a));
            return textView;
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new DividerHorizenLineItemDecoration(this)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(this, 1))
                .setPaintColor(ContextCompat.getColor(this, R.color.divider_s))
                .setTopPadding((int) RudenessScreenHelper.pt2px(this, 20))
                .setBottomPadding((int) RudenessScreenHelper.pt2px(this, 20))
                .setFirstDraw(false)
                .setLastDraw(false));
        ClickUtil.click(300, ivTurnTable, () -> {

//            TipUtil.qrcode(this, "http://imgsa.baidu.com/exp/w=500/sign=59f1f40178f40ad115e4c7e3672d1151/0d338744ebf81a4c02852ff0d42a6059252da650.jpg");
            mPresenter.getAddresses(SPUtil.get(SPConfig.ID, ""));
        });
        ClickUtil.click(300, viewGerenziliao, () -> UserInfoActivity.start(this));
        ClickUtil.click(300, viewZhanghaoanquan, () -> AccountSafeActivity.start(this));
        ClickUtil.click(300, viewZhanghaozichan, () -> AssetActivity.start(this));
        ClickUtil.click(300, viewDingdanguanli, () -> OrderManagerActivity.start(this));
        ClickUtil.click(300, viewWodetuandui, () -> MySpreadActivity.start(this));
        ClickUtil.click(300, viewTuichu, () -> {
            LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
            logoutProvider.logout();
            finish();
        });
        ClickUtil.click(300, viewClick, () -> {
            if (isEmpty(dragonName)) {
                return;
            }
            switch (dragonStatus) {
                case Constans.DRAGON_YUE:
                    //预约龙弹窗
                    TipUtil.reserveTip(MainActivity.this, dragonName, dragonDays, yuyueMoney, () -> {
                        mPresenter.reservationDragon(dragonID, SPUtil.get(SPConfig.ID, ""));
                    });
                    break;
                case Constans.DRAGON_START:
                    //抢购龙
                    mPresenter.buyDragon(dragonID, SPUtil.get(SPConfig.ID, ""));
                    break;
                default:
                    break;
            }
        });

        isCheck.add(0);
        slimAdapter = SlimAdapter.create().register(R.layout.item_dragon_time, new SlimInjector<DragonBean>() {
            @Override
            public void onInject(DragonBean data, IViewInjector injector, List payloads) {
                injector.text(R.id.tv_time, data.getDealStartTime() + "-" + data.getDealEndTime())
                        .text(R.id.tv_dragon, data.getName());
                if (isCheck.contains(slimAdapter.getData().indexOf(data))) {
                    injector.background(R.id.tv_dragon, R.drawable.btn_bg_blue);
                } else {
                    injector.background(R.id.tv_dragon, null);
                }
                injector.clicked(R.id.constraint, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isCheck.contains(slimAdapter.getData().indexOf(data))) {
                            return;
                        } else {
                            isCheck.clear();
                            isCheck.add(slimAdapter.getData().indexOf(data));
                            injector.background(R.id.tv_dragon, R.drawable.btn_bg_blue);
                            slimAdapter.notifyDataSetChanged();
                            changeDragonImg(data.getName(), ivDragon);
                            mPresenter.getDragonsMsg(data.getId(), true);
                        }
                    }
                });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.updata(APKVersionCodeUtils.getVerName(this));
        mPresenter.getDragons(null);
        mPresenter.getNotices();
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
            if (userData != null) {
                mPresenter.getAsset(userData.getId(), null);
                tvName.setText(isEmpty(userData.getNickname()) ? "默认用户" : userData.getNickname());
                tvId.setText(userData.getUserUid());
                ImageUtil.setCircleImage(userData.getHeadUrl().contains("http") ? userData.getHeadUrl() : HttpConfig.BASE_URL + userData.getHeadUrl(), ivHead);
            }
        });
        tvVersion.setText(App.INSTANCE.getString(R.string.bottom1) + APKVersionCodeUtils.getVerName(this));

        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                mPresenter.getDragons(refreshView);
                if (userData != null) {
                    mPresenter.getAsset(userData.getId(), refreshView);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DisposUtil.close(noticeDispo);
        if (disposableSubscriber != null) {
            if (!disposableSubscriber.isDisposed()) {
                disposableSubscriber.dispose();
                disposableSubscriber = null;
            }
        }
    }

    public void updataAsset(AssetBean assetBean) {
        if (assetBean == null) {
            return;
        }
        tvQuan.setText(assetBean.getRaffleTickets());
        tvShuijing.setText(NumberUtil.keep2(assetBean.getCrystalCoin()));
    }

    public void updataDragons(List<DragonBean> dragonBeans) {
        if (dragonBeans != null && dragonBeans.size() > 0 && slimAdapter != null) {
            slimAdapter.updateData(dragonBeans);
            if (isEmpty(dragonID)) {
                dragonID = dragonBeans.get(0).getId();
                mPresenter.getDragonsMsg(dragonBeans.get(0).getId(), true);
            } else {
                mPresenter.getDragonsMsg(dragonID, false);
            }
        }
    }

    public void updataDragonMsg(DragonBean dragonBean) {
        if (dragonBean == null) {
            return;
        }
        if (disposableSubscriber != null) {
            if (!disposableSubscriber.isDisposed()) {
                disposableSubscriber.dispose();
                disposableSubscriber = null;
            }
        }
        yuyueMoney = NumberUtil.keep2(dragonBean.getAdvancePrice());
        qianggouMoney = NumberUtil.keep2(dragonBean.getRushPurchasePrice());
        dragonName = dragonBean.getName();
        dragonID = dragonBean.getId();
        draggonMoney = dragonBean.getAdvancePrice();
        dragonDays = dragonBean.getContractDays();
        tvDragonName.setText(dragonBean.getName());
        changeDragonImg(dragonBean.getName(), ivDragon);
        tvDragonDays.setText(dragonBean.getContractDays() + App.INSTANCE.getString(R.string.tian));
        tvDragonIncome.setText(NumberUtil.keepNoZero(dragonBean.getProfitRatio()) + "%");
        tvDragonMoney.setText("￥" + NumberUtil.keep2(dragonBean.getMinPrice()) + "-￥" + NumberUtil.keep2(dragonBean.getMaxPrice()));
        if (dragonBean.getTime1().equals("0") && dragonBean.getTime2().equals("0") && dragonBean.getTime3().equals("0")) {
            viewClick.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.bg_yuyue_gray));
            viewClick.setEnabled(false);
            tvDragonStatus.setText(App.INSTANCE.getString(R.string.appYijieshu));
            tvDragonTimes.setVisibility(View.GONE);
            tvDragonTimes.setText("");
            dragonStatus = Constans.DRAGON_OVER;
            return;
        }
        if (Long.valueOf(dragonBean.getTime1()) > 0) {
            viewClick.setEnabled(true);
            startTimeDown(Long.valueOf(dragonBean.getTime1()), null);
            viewClick.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.bg_main));
            tvDragonStatus.setText(App.INSTANCE.getString(R.string.appLijiyuyue));
            tvDragonTimes.setText("");
            tvDragonTimes.setVisibility(View.GONE);
            dragonStatus = Constans.DRAGON_YUE;
            return;
        }
        if (Long.valueOf(dragonBean.getTime2()) > 0) {
            tvDragonTimes.setVisibility(View.VISIBLE);
            startTimeDown(Long.valueOf(dragonBean.getTime2()), tvDragonTimes);
            viewClick.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.bg_yuyue_gray));
            viewClick.setEnabled(false);
            tvDragonStatus.setText(App.INSTANCE.getString(R.string.appLijiqianggou));
            dragonStatus = Constans.DRAGON_WAIT;
            return;
        }
        if (Long.valueOf(dragonBean.getTime3()) > 0) {
            startTimeDown(Long.valueOf(dragonBean.getTime3()), null);
            viewClick.setBackground(ContextCompat.getDrawable(App.INSTANCE, R.mipmap.bg_main));
            viewClick.setEnabled(true);
            tvDragonStatus.setText(App.INSTANCE.getString(R.string.appLijiqianggou));
            tvDragonTimes.setVisibility(View.GONE);
            tvDragonTimes.setText("");
            dragonStatus = Constans.DRAGON_START;
            return;
        }
    }

    protected DisposableSubscriber<Long> disposableSubscriber;

    public void startTimeDown(Long totalLong, TextView textView) {
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                long time = (int) (totalLong - aLong);
                if (tvCountDown != null) {
//                    tvCountDown.setText(String.valueOf(time));
                }
                if (textView != null) {
                    textView.setText(App.INSTANCE.getString(R.string.appKaishoushijian) + TimeFormatUtil.parseTime(time));
                }
                if (time == 1) {
                    mPresenter.getDragonsMsg(dragonID, true);
                }
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };

        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(totalLong)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    public void changeDragonImg(String dragonName, ImageView imageView) {
        switch (dragonName) {
            case "创世龙":
                imageView.setImageResource(R.mipmap.img_dragon_chuangshi);
                break;
            case "傲视龙":
                imageView.setImageResource(R.mipmap.img_dragon_cn);
                break;
            case "净世龙":
                imageView.setImageResource(R.mipmap.img_dragon_jingshi);
                break;
            case "救世龙":
                imageView.setImageResource(R.mipmap.img_dragon_jiushi);
                break;
            case "炼世龙":
                imageView.setImageResource(R.mipmap.img_dragon_lianshi);
                break;
            case "灭世龙":
                imageView.setImageResource(R.mipmap.img_dragon_mieshi);
                break;
            case "弃世龙":
                imageView.setImageResource(R.mipmap.img_dragon_qishi);
                break;
            case "治世龙":
                imageView.setImageResource(R.mipmap.img_dragon_zhishi);
                break;
            default:
                break;
        }
    }

    public void reservationOK() {
        TipUtil.reserveSuccess(MainActivity.this, dragonName);
    }

    public void buyDragonOK(RushDragonBean rushDragonBean) {
        if (rushDragonBean != null) {
            TipUtil.buyTip(MainActivity.this, dragonName, rushDragonBean.getContractDays(), rushDragonBean.getPrice(), rushDragonBean.getRuchPrice());
        }
    }

    public void updataNotices(List<NoticeBean> noticeBeans) {
        if (noticeBeans == null) {
            return;
        }
        if (tvNotice != null) {
            if (noticeBeans.size() > 0) {
                DisposUtil.close(noticeDispo);
                noticeDispo = Flowable.interval(0, 5, TimeUnit.SECONDS)
                        .onBackpressureDrop()
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(i -> {
                            if (tvNotice != null) {
                                noticeBean = noticeBeans.get((int) (i % noticeBeans.size()));
                                tvNotice.setText(noticeBean.getDetails());
//                                ClickUtil.click(tvNotice, () -> {
//                                    ARouter.getInstance()
//                                            .build(RConfig.APP_GUIDE_WEB)
//                                            .withString(Constans.HEAD, App.INSTANCE.getString(R.string.appJavaGuideListFragment8))
//                                            .withString(Constans.ID, noticeList.getId())
//                                            .withString(Constans.TIME, noticeList.getCreate_time())
//                                            .withString(Constans.TITLE, noticeList.getTitle())
//                                            .navigation();
//                                });
                            }
                        }, System.out::println);
            }
        }

    }

    public void getAddressOK(List<AddressBean> data) {
        if (data == null || data.size() == 0) {
            ToastUtil.showShort(App.INSTANCE.getString(R.string.appMeiyoushouhuodizhi));
            return;
        }
        TurntableActivity.start(this);
    }

    public void needUpdata(UpdataBean updataBean) {
        if (updataBean == null) {
            return;
        }
//        if (updataBean.getUptype().equals("2")) {
//            updataBean.isMustUp();
//        }
        String verName = APKVersionCodeUtils.getVerName(this);
        updataBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(updataBean.getVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, updataBean);
            appUpDateFragment.setArguments(bundle);
            fragmentTransaction.add(appUpDateFragment, "updateUI");
            fragmentTransaction.commitAllowingStateLoss();
        } else {
        }

    }

}
